<?php

App::uses('AppModel', 'Model');

class Leave extends AppModel {
	
	public $belongsTo = array( 'User', 'LeaveType');
	public $errors    = array();
	public $order     = "Leave.start DESC, Leave.id DESC";
	
	public $validate = array(
		'leave_type_id' => array(
            'rule'    => 'applyRules',
            'message' => 'Rules violation error.'
		)
	);
	
	public function setApproved($approved) {
	    if (! empty($this->data)) {
	        $this->data['Leave']['approved'] = $approved;
	    }
	}
	
	public function applyRules() {
	    $this->errors = array();
	    $data = $this->data['Leave'];
	    $LeaveType = $this->LeaveType->findById($data['leave_type_id']);
	    
	    $ret = true;
	    foreach ($LeaveType['LeaveTypeRule'] as $rule) {
	        $ret2 = $this->applyRule($rule);
	        $ret = $ret && $ret2;
	    }
	    
	    return $ret;
	}
	
	public function applyRule($rule) {
	    $obj = $this->getRule($rule['rule']);
	    call_user_method_array('apply', $obj, array_merge(array($this), $rule['arguments']));
	    
	    $success = empty($obj->error);
	    if (! $success) {
	        $this->errors[] = $obj->error;
	    }
	    return $success;
	}
    
    public function runsDuringHoliday($start, $end) {
        $sql = "SELECT 1 ".
               "FROM holidays ".
               "WHERE '%s' <= `end` AND '%s'>= `start` ".
               "LIMIT 1";
        $res = $this->query(sprintf($sql, $start, $end));
        
        return !empty($res);
    }
    
    public function getUsersBetween($start, $end) {
        $num = (int)$this->find('count', array(
            'end   >=' => $start,
            'start <=' => $end
        ));
        
        return $num;
    }
    
    public function findUserLeaveDaysBetween($userId, $start, $end) {
        $days = 0;
        $res = $this->find('all', array(
            'conditions' => array(
                'Leave.user_id' => $userId,
                'Leave.end >='  => $start,
                'Leave.start <='=> $end,
                'Leave.approved' => 1
            )
        ));
        foreach ($res as $row) {
            $days += $this->daysBetween($row['Leave']['start'], $row['Leave']['end']);
        }
        
        return floor($days);
    }
    
    public function daysBetween($start, $end) {
        $s = strtotime($start);
        $e = strtotime($end);
        $d = ($e-$s)/DAY + 1;
        
        return $d>0 ? $d : 1;
    }
}

?>